<template>
	<el-dialog v-model="isVisible" :title="props.row ? '编辑价格' : '新增价格'" width="500px" :before-close="handleClose">
		<el-form ref="formRef" class="good-service-form" :model="form" :rules="rules" label-width="120px" inline>
			<el-form-item label="价格" prop="price">
				<el-input-number class="num-left" :controls="false" :min="0" v-model="form.price" />
			</el-form-item>
			<el-form-item label="价格日期" prop="priceDate">
				<el-date-picker v-model="form.priceDate" />
			</el-form-item>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="handleClose">取消</el-button>
				<el-button type="primary" v-debounce="submit">保存</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script setup lang="tsx">
import { FormRules, ElMessage, dayjs } from 'element-plus';
import { onMounted, ref, reactive, watch } from 'vue';
import { fetchCreatePrice, fetchPriceDetail, fetchUpdatePrice } from '/@/api/goods';
import { useRoute, useRouter } from 'vue-router';
import { fenToYuan } from '/@/utils/commonFunction';
const route = useRoute();

const props = defineProps({
	// 列表内容
	visible: {
		type: Boolean,
		default: () => false,
	},
	row: {
		type: Object,
		default: () => null,
	},
});

const emit = defineEmits(['handleClose']);

const isVisible = ref(false);

const formRef = ref();
const form = ref<any>({
	price: '',
	priceDate: '',
});

//校验规则
const rules = reactive<FormRules<any>>({
	price: [{ required: true, trigger: 'blur', message: '价格不能为空' }],
	priceDate: [{ required: true, trigger: 'blur', message: '价格日期不能为空' }],
});

watch(
	() => props.visible,
	async (val) => {
		if (val && props.row) {
			const res = await fetchPriceDetail({ id: props.row.id });
			if (res.code === 200) {
				form.value = res.data;
				form.value.price = fenToYuan(form.value.price);
			}
		}
		isVisible.value = val;
	},
	{
		immediate: true,
	}
);

const submit = async () => {
	formRef.value.validate(async (valid: boolean) => {
		if (valid) {
			const params = { ...form.value, productId: route.params.id };
			params.price = params.price * 100;
			params.priceDate = dayjs(params.priceDate).format('YYYY-MM-DD HH:mm:ss');
			const res = props.row?.id ? await fetchUpdatePrice(params) : await fetchCreatePrice(params);
			if (res.code == 200) {
				ElMessage.success(props.row?.id ? '编辑价格成功' : '新增价格成功');
				handleClose(true);
			} else {
				ElMessage.error(res.msg);
			}
		}
	});
};

const handleClose = (success?: boolean) => {
	form.value = {};
	formRef.value.resetFields();
	emit('handleClose', success === true);
};
</script>

<style lang="scss">
.good-service-form {
	.el-form-item {
		width: 90%;
		.el-input-number,
		.el-input {
			width: 100%;
		}
	}
}
</style>
